<?php
/**
 * vanephp web framework
 * 数据库工具
 *
 * @author aray <ofree@qq.com>
 * @link http://www.vanephp.com/s
 * @copyright Copyright &copy; 2010 aray
 * @license http://www.vanephp.com/license
 * @package core
 */

if ( ! defined ( 'INVANE' ) )
	exit ( '!' );

/**
 * 数据库工具类
 * @author aray
 * @abstract
 */
abstract class dbo {
	private static $dsn = array ();
	private static $link = array ();
	/**
	 * 获取数据库连接
	 */
	final public static function getDbo ( ) {
		if ( empty ( self::$dsn ) ) {
			self::change ( 0 );
		}
		return vane::singleton ( config::get ( 'db_driver' ), self::$dsn )->connect ( );
	}
	/**
	 * 获取当前DSN
	 */
	final public static function getDSN ( ) {
		if ( empty ( self::$dsn ) )
			self::change ( 0 );
		return self::$dsn;
	}
	/**
	 * 切换数据库
	 * @param int $index	数据库配置索引
	 */
	final public static function change ( $index ) {
		$dsn = config::get ( 'config', 'dsn' );
		if ( $dsn && isset ( $dsn[$index] ) )
			self::$dsn = $dsn[$index];
		else
			self::$dsn = $dsn[0];
		self::getDBO ( )->setCharset ( );
	}
	/**
	 * 查询SQL
	 * @param string $sql
	 */
	final public static function query ( $sql ) {
		$query = self::getDbo ( )->query ( $sql );
		return $query;
	}
	/**
	 * 查询SQL并返回所有行
	 * @param string $sql	SQL语句
	 */
	final public static function getAll ( $sql ) {
		return self::getDbo ( )->getAll ( $sql );
	}
	/**
	 * 查询SQL并返回第一行
	 * @param string $sql	SQL语句
	 */
	final public static function getOne ( $sql ) {
		return self::getDbo ( )->getOne ( $sql );
	}
	/**
	 * 查询SQL并返回第一行第一列
	 * @param string $sql
	 */
	final public static function getCol ( $sql ) {
		return self::getDbo ( )->getCol ( $sql );
	}
	/**
	 * 获取表的字段信息
	 * @param string $table	数据表名称
	 * @return array
	 */
	final public static function getTableMeta ( $table ) {
		return self::getDbo ( )->getTableMeta ( $table );
	}
	/**
	 * 获取上次insert操作插入的ID
	 * @return int
	 */
	final public static function getLastInsertId ( ) {
		return self::getDbo ( )->getLastInsertId ( );
	}
	/**
	 * 获取上次update操作影响的行数
	 * @return int
	 */
	final public static function getAffected ( ) {
		return self::getDbo ( )->getAffected ( );
	}
	/**
	 * 获取数据库SCHEMA
	 */
	final public static function getDbSchema ( ) {
		return self::getDBO ( )->getDbSchema ( );
	}
}